package com.bto.solar.work.service;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bto.solar.work.common.BizException;
import com.bto.solar.work.constant.DBConstants;
import com.bto.solar.work.dao.IOrderBaseService;
import com.bto.solar.work.dao.IReconnoitreService;
import com.bto.solar.work.dao.IRecordService;
import com.bto.solar.work.entity.Company;
import com.bto.solar.work.entity.LeaseLessor;
import com.bto.solar.work.entity.OrderBase;
import com.bto.solar.work.entity.Reconnoitre;
import com.bto.solar.work.entity.Record;
import com.bto.solar.work.entity.User;
import com.bto.solar.work.utils.NullUtils;
import com.bto.solar.work.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author 王小波
 * @description:
 * @date 2023/8/19 16:39
 */
@Service
public class BtoRecordService {
    @Autowired
    private IRecordService recordService;
    @Autowired
    private IOrderBaseService orderBaseService;
    @Autowired
    private IReconnoitreService reconnoitreService;
    @Autowired
    private BtoUserService btoUserService;
    @Autowired
    private BtoCompanyService btoCompanyService;
    @Autowired
    private BtoPermissionService btoPermissionService;
    @Autowired
    private BtoLeaseLessorService btoLeaseLessorService;

    public Record createRecord(Record record) {
        Record byId = recordService.getById(record.getRecordCertificateId());
        if (NullUtils.isNotNull(byId)) {
            throw new BizException("备案证编号 {} 已存在", record.getRecordCertificateId());
        }
        //获取当前登录者
        User loginUser = btoUserService.getCurrentUser();
        String permissionList = loginUser.getPermissionIds();
        if (!permissionList.contains(DBConstants.PER_BAZXX)) {
            throw new BizException("你没有权限新增备案证");
        }
        if (1 == record.getRecordType()) {
            record.setSurplusCapacity(record.getRecordCertificateCapacity());
        }
        record.setUserId(loginUser.getUserId());
        recordService.save(record);
        return record;
    }

    public Record updateRecord(Record record) {
        //校验当前登录者是否有备案证管理员权限
        User loginUser = btoUserService.getCurrentUser();
        String permissionList = loginUser.getPermissionIds();
        if (!permissionList.contains(DBConstants.PER_BAZXX)) {
            throw new BizException("你没有权限修改备案证");
        }

        //更新容量时需要做检查
        if (NullUtils.isNotNull(record.getRecordCertificateCapacity())) {
            Record recordDb = recordService.getById(record.getRecordCertificateId());

            //如果这个备案证不属于你 并且你也不属于总部公司，无法修改。
            if (!recordDb.getUserId().equals(loginUser.getUserId()) && !btoUserService.isUserBelongHeadCompany(loginUser)) {
                User user = btoUserService.getUserByUserId(recordDb.getUserId());
                throw new BizException("该备案证{}属于{}，无权修改", recordDb.getRecordCertificateId(), user.getName());
            }

            //更新剩余容量
            Integer changedCapacity =  record.getRecordCertificateCapacity() - recordDb.getRecordCertificateCapacity();
            record.setSurplusCapacity(recordDb.getSurplusCapacity() + changedCapacity);

            Integer used = recordDb.getRecordCertificateCapacity() - Optional.ofNullable(recordDb.getSurplusCapacity()).orElse(0);
            //如果已经使用的容量大于，新更新的容量。 不做限制
            if (used > record.getRecordCertificateCapacity()) {
//                throw new BizException("更新容量{}小于，已使用容量{}", record.getRecordCertificateCapacity(), used);
            }


        }
        recordService.updateById(record);
        return record;
    }

    public void deleteRecord(String recordId) {
        List<OrderBase> orderBaseList = orderBaseService.lambdaQuery()
                .eq(OrderBase::getRecordCertificateId, recordId).list();

        if (NullUtils.isNotEmpty(orderBaseList)) {
            throw new BizException("备案证{} 已被项目使用，无法删除");
        }
        recordService.removeById(recordId);
    }

    public Record getRecordById(String recordCertificateId) {
        Record record = recordService.getById(recordCertificateId);
        if (NullUtils.isNull(record)) {
            throw new BizException("不存在备案证 {}", recordCertificateId);
        }

        return record;
    }


    public List<Record> getRecords(Record record, boolean isAuth) {

        User user = btoUserService.getCurrentUser();
        Company company = btoCompanyService.getCompanyByUser(user);

        //超级管理员或者总部公司 -- 忽略是否有权限
        if (user.getRolesIds().contains(DBConstants.ROLE_SUPER_ADMIN)
                || DBConstants.COMPANY_TYPE_HEAD_OFFICE.equals(company.getType())) {
            return getRecordListByLike(record);
        }
        //需要权限
        if (isAuth) {
            List<Record> records = getRecordListByLike(record);
            List<Record> result = new ArrayList<>();
            records.forEach(dbRecord -> {
                if (StringUtils.isNotBlank(dbRecord.getAccreditCompanyIds())) {
                    List<Long> companyIds = JSONArray.parseArray(dbRecord.getAccreditCompanyIds(), Long.class);
                    if (NullUtils.isNotEmpty(companyIds)) {
                        if (companyIds.contains(company.getCompanyId())) {
                            result.add(dbRecord);
                        }
                    }
                }
            });
            return result;
        } else {
            return getRecordListByLike(record);
        }
    }

    //备案证的模糊查询
    public List<Record> getRecordListByLike(Record record) {
        //备案证编码
        String recordCertificateId = null;
        //项目公司
        List<String> companyIds = new ArrayList<>();
        if (null != record) {
            recordCertificateId = record.getRecordCertificateId();
            if (StringUtils.isNotBlank(recordCertificateId)) {
                record.setRecordCertificateId(null);
                companyIds = btoLeaseLessorService.getCompanyByName(recordCertificateId).stream().map(LeaseLessor::getCode).collect(Collectors.toList());
            } else {
                record.setRecordCertificateId(null);
            }
        }

        return recordService.lambdaQuery().setEntity(record)
                .like(StringUtils.isNotBlank(recordCertificateId), Record::getRecordCertificateId, recordCertificateId)
                .or()
                .in(NullUtils.isNotEmpty(companyIds), Record::getCompanyId, companyIds)
                .list();
    }

    public JSONObject getRecordCount() {
        long bigCount = recordService.count(new LambdaQueryWrapper<Record>().eq(Record::getRecordType, 1));
        long perCount = recordService.count(new LambdaQueryWrapper<Record>().eq(Record::getRecordType, 2));
        JSONObject result = new JSONObject();
        result.put("bigRecordCnt" , bigCount);
        result.put("perRecordCnt" , perCount);

        return result;
    }


    /**
    *  备案证容量更新
     * 提交时扣除容量
     * 切换备案证时，退还容量
    */
    public void updateRecordSurplusCapacity(Record record , OrderBase orderBase){
        //精准备案不计算容量
        if(1 != record.getRecordType()){
            return;
        }
        Reconnoitre reconnoitre = reconnoitreService.getById(orderBase.getOrderId());

        if(NullUtils.isNull(reconnoitre)){
            throw new BizException("没有找到该订单 {} ，勘察信息，无法匹配大备案证" , orderBase.getOrderId());
        }
        if(!orderBase.getRecordCertificateId().equals(record.getRecordCertificateId())){
            //退还容量
            Record preRecord = recordService.getById(orderBase.getRecordCertificateId());
            preRecord.setSurplusCapacity(preRecord.getSurplusCapacity() + reconnoitre.getInstalledCapacityReckon());

            //扣除剩余容量
            if(StringUtils.isNotEmpty(record.getRecordCertificateId())){
                Integer surplus =  record.getSurplusCapacity() - reconnoitre.getInstalledCapacityReckon();
                //剩余容量可以为负数
//                if(surplus < 0){
//                    throw new BizException("备案证剩余容量 {} 不够订单拟安装容量{}" , record.getSurplusCapacity()  , reconnoitre.getInstalledCapacityReckon());
//                }
                record.setSurplusCapacity(surplus);
                recordService.updateById(record);
            }

            recordService.updateById(preRecord);
        }
    }



}
